var language;

function ShowLoadingIndicator() {
    if (typeof (disableLoadingIndicator) != 'undefined' && disableLoadingIndicator) {
        return;
    }
    var windowWidth = $j(window).width();
    var scrollTop;
    if (self.pageYOffset) {
        scrollTop = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    }
    else if (document.body) {
        scrollTop = document.body.scrollTop;
    }
    $j('#AjaxLoading').css('position', 'absolute');
    $j('#AjaxLoading').css('top', scrollTop + 'px');
    $j('#AjaxLoading').css('left', parseInt((windowWidth - 150) / 2) + "px");
    $j('#AjaxLoading').show();
}

function HideLoadingIndicator() {
    $j('#AjaxLoading').delay(800).slideUp(300);
}

$j(function () {
    if (language == "vi-VN")
        $j("#AjaxLoading").html("<img src=\"/images/ajax-load.gif\" />&nbsp; Đang tải... Vui lòng chờ...");
    else
        $j("#AjaxLoading").html("<img src=\"/images/ajax-load.gif\" />&nbsp; Loading... Please wait...");

    $j('html').ajaxStart(function () {
        ShowLoadingIndicator();
    });
    $j('html').ajaxComplete(function () {
        HideLoadingIndicator();
    });
    $j('.InitialFocus').focus();
});

function PopupCartAmount(id, amount) {
    var optionVars = "0";
    if ($j(".CartOptionId").length > 0) { optionVars = $j(".CartOptionId").val(); }
    $j.ajax({
        beforeSend: function () { },
        type: "POST",
        url: "/WebServices/ProductService.asmx/ViewProductCart",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{'productId':'" + id + "', 'productAmount':'" + amount + "', 'optionVars':'" + optionVars + "'}",
        success: function (response) {
            $j('#inline1').html(response.d);
        },
        failure: function (msg) { console.log(msg); },
        error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status + ': ' + thrownError); },
        complete: function (msg) { ReloadCart(); },
        afterClose: function () { $j('#inline1').html(""); }
    });
    return false;
}

function PopupCart(id) {
    var displayPopup = true;
    var popupcontent = $j("#inline1").html();
    if (popupcontent != "") {
        var productId = Number($j(".popup-cart").find(".fastCartTop").attr("productid"));
        if (productId == id) { displayPopup = false; }
    }
    if (displayPopup == true) {
        $j.ajax({
            beforeSend: function () { },
            type: "POST",
            url: "/WebServices/ProductService.asmx/ViewProductCart",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{'productId':'" + id + "', 'productAmount':'1', 'optionVars':''}",
            success: function (response) { $j('#inline1').html(response.d); },
            failure: function (msg) { console.log(msg); },
            error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status + ': ' + thrownError); },
            complete: function (msg) { ReloadCart(); }
        });
        $j("a.ProductAddButton").trigger("click");
    }
    else {
        $j.ajax({
            beforeSend: function () { },
            type: "POST",
            url: "/WebServices/ProductService.asmx/UpdateProductAmount",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{'productId':'" + id + "'}",
            success: function (response) { },
            failure: function (msg) { console.log(msg); },
            error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status + ': ' + thrownError); },
            complete: function (msg) { ReloadCart(); }
        });

        var quantity = Number($j(".quantity").find("span").html());
        quantity = quantity + 1;
        $j(".quantity").find("span").html(quantity);

        var sum = Number($j("#fastCartNumItemsTxt").html());
        sum = sum + 1;
        $j("#fastCartNumItemsTxt").html(sum);
    }
    return false;
}

function ReloadCart() {
    $j.ajax({
        type: "POST",
        url: "/WebServices/ProductService.asmx/LoadCart",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            $j('#plist').fadeTo("slow", 0.8);
            $j('#plist').html(response.d);
            $j('#plist').fadeTo('slow', 1);
        },
        failure: function (msg) { console.log(msg); },
        error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status + ': ' + thrownError); },
        complete: function (msg) {
            if ($j("#pInCart").html() != null)
                $j("#pInTop").html(' (' + $j("#pInCart").html() + ')');
            else $j("#pInTop").html('');
        }
    });
}

function RemoveProductCart(position) {
    $j.ajax({
        beforeSend: function () { },
        type: "POST",
        url: "/WebServices/ProductService.asmx/RemoveProductInCart",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{'position':'" + position + "'}",
        success: function (response) {
            $j('#plist').fadeTo("slow", 0.8);
            $j('#plist').html(response.d);
            $j('#plist').fadeTo("slow", 1);
        },
        failure: function (msg) { console.log(msg); },
        error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status + ': ' + thrownError); },
        complete: function (msg) {
            if ($j("#pInCart").html() != null) $j("#pInTop").html(' (' + $j("#pInCart").html() + ')');
            else $j("#pInTop").html('');
            if ($j(".CartContents").html() != null) {
                window.location.reload();
            }
        }
    });

    return false;
}

///// FUNCTION FOR UPDATE SHOPPING CART /////
function money2number(money) {
    //check number after "."
    var num = money.substring(money.lastIndexOf(".") + 1, money.length);
    //alert(num+" / "+ num.length);
    if (num.length == 3) {
        return money.replace(".", "", "g");
    } else {
        return money.replace(",", "", "g");
    }
}

function checkRegion() {
    var number = $j("#grandTotal").html();
    var num = number.substring(number.lastIndexOf(".") + 1, number.length);
    if (num.length == 3) {
        return "vi-VN";
    } else {
        return "en-US";
    }
}

function FormatCurrency(num) {
    var culture = checkRegion();
    if (culture == "vi-VN") {
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num)) num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10) cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
        return (((sign) ? '' : '-') + num);
    } else {
        //format USD - EUR 
        return num.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
    }

}
/////END FUNCTION FOR UPDATE SHOPPING CART /////


function PopupCartDetail() {
    var inventory = $j('.VariationProductInventory').html();
    var amount = $j("[id$='qty_']").val();
    if (Number(amount) > Number(inventory)) {
        alert('Số lượng đặt mua không được lớn hơn số lượng còn trong kho !');
    }
    else {
        if (amount <= 0)
        {
            alert('Số lượng đặt mua không được nhỏ hơn 0 !');
        }
        else
        {
            $j(".BulkDiscount").hide();
            PopupCartAmount(ProductId, amount);
            $j(".BulkDiscount").show();
            $j("a.ProductAddButton").trigger("click");
        }
    }
}

$j(function () {
    $j("a.ProductAddButton").fancybox({
        width: 800, height: 550, fitToView: false, autoSize: false, openEffect: "fade", closeEffect: "fade",
        afterClose: function () {
            $j("#inline1").html("");
        }
    });
});

function check_add_to_cart(form, required) {
    // validate the attributes
    var attributesValidated = $j('form')
		.validate().form();

    if (!attributesValidated) {
        return false;
    }

    //popup cart
    PopupCartDetail();
    return false;
}

$j(document).ready(function () {
    var menus = $j("#nav ul.level0");
    menus.each(function (index, menu) {
        var childs = $j(menu).children().length;
        if (childs == 0) $j(menu).remove()
    });
    menus = $j("#nav ul.level1"); menus.each(function (index, menu) {
        var childs = $j(menu).children().length;
        if (childs == 0) $j(menu).remove()
    })
});

function toggleMenu(el1, el2, over) {
    var p; var prefix = "nav-";
    if (el2 == -1) { p = document.getElementById(prefix + el1) }
    else { p = document.getElementById(prefix + el1 + "-" + el2) }
    var newClassName;
    if (over == 1) {
        newClassName = p.className + " over"; p.className = newClassName
    }
    else {
        newClassName = p.className.replace(" over", ""); p.className = newClassName
    }
}

function keypress(e) {
    var keypressed = null;
    if (window.event) {
        keypressed = window.event.keyCode; //IE
    }
    else {
        keypressed = e.which; //NON-IE, Standard
    }
    if (keypressed < 48 || keypressed > 57) {
        if (keypressed == 8 || keypressed == 127 || keypressed == 0) { return; }
        return false;
    }
}